﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CITWebsite.Models;
using DTO.Models;
using System.IO;
using CITWebsite.Helper;

namespace CITWebsite.Controllers
{
    public class UserController : Controller
    {
        private bool CheckAdmin()
        {
            //if (Session[Common.SessionCookiesUserType] == null)
            //    return false;
            //else
            //{
                string userType = Session[Common.SessionCookiesUserType].ToString();
                if (!userType.Equals(UserType.admin.ToString()))
                    return false;
            //}

            return true;
        }

        [Authorize]
        public ActionResult Index()
        {
            if (Session[Common.SessionCookiesUserType] == null)
            {
                return RedirectToAction("LogOff", "Account");
            }
            else
            {
                if (!CheckAdmin())
                {
                    ViewData["Message"] = "QUẢN LÝ DANH SÁCH NGƯỜI DÙNG";
                    return View("NoPermission");
                    //return RedirectToAction("Index", "Home");
                }
            }
            return View();

        }

        [Authorize]
        [HttpGet]
        public ActionResult List(string id, string pPageIndex, string userName, string fullName)
        {
            if (!CheckAdmin())
                return RedirectToAction("Index", "Home");

            int PageSize = Common.pagesize;
            int PageIndex = Convert.ToInt32(pPageIndex);

            DataRepository dr = new DataRepository();
            var source = dr.UserProvider.GetAll(userName, fullName);
            var model = source.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToArray();

            int len = source.ToList<USER>().Count;
            ViewData["TotalPage"] = (len % PageSize == 0 ? len / PageSize : len / PageSize + 1).ToString();
            ViewData["PageIndex"] = PageIndex.ToString();
            ViewData["PageSize"] = PageSize.ToString();
            ViewData["TypeMediaName"] = id;

            return View(model);
        }

        [Authorize]
        public ActionResult AddUpdateUser(string id)
        {
            if (!CheckAdmin())
                return RedirectToAction("Index", "Home");

            //  init user type combo box
            SelectListItem typeUser = new SelectListItem();
            typeUser.Text = UserType.user.ToString();
            typeUser.Value = UserType.user.ToString();
            SelectListItem typeAdmin = new SelectListItem();
            typeAdmin.Text = UserType.admin.ToString();
            typeAdmin.Value = UserType.admin.ToString();
            List<SelectListItem> listUserType = new List<SelectListItem>();
            listUserType.Add(typeUser);
            listUserType.Add(typeAdmin);
            ViewData["ListUserType"] = new SelectList(listUserType, "Value", "Text");


            USER obj = null;
            //add new
            if (id == "0")
            {
                obj = new USER(0, "", "", "", false);
            }
            else
            {
                DataRepository dr = new DataRepository();
                obj = dr.UserProvider.GetUserById(Convert.ToInt32(id));
            }

            return View(obj);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddUpdateUser(USER obj)
        {
            if (!CheckAdmin())
                return RedirectToAction("Index", "Home");

            if (!ModelState.IsValid)
            {
                //  init user type combo box
                SelectListItem typeUser = new SelectListItem();
                typeUser.Text = UserType.user.ToString();
                typeUser.Value = UserType.user.ToString();
                SelectListItem typeAdmin = new SelectListItem();
                typeAdmin.Text = UserType.admin.ToString();
                typeAdmin.Value = UserType.admin.ToString();
                List<SelectListItem> listUserType = new List<SelectListItem>();
                listUserType.Add(typeUser);
                listUserType.Add(typeAdmin);
                ViewData["ListUserType"] = new SelectList(listUserType, "Value", "Text");

                return View(obj);
            }

            DataRepository dr = new DataRepository();
            string passwordencrypt = MD5.Encrypt(obj.Password, obj.UserName + "key", true);
            obj.Password = passwordencrypt;
            if (obj.ID == 0)    // insert
                dr.UserProvider.insert(obj);
            else
                dr.UserProvider.update(obj.ID, obj.UserName, obj.Password, obj.FullName, obj.Type, obj.IsActive ?? false);

            return RedirectToAction("Index");
        }

        [Authorize]
        public ActionResult Delete(string id)
        {
            if (!CheckAdmin())
                return RedirectToAction("Index", "Home");

            DataRepository dr = new DataRepository();
            dr.UserProvider.DeleteMark(id);

            return Content("");
        }

        [Authorize]
        public ActionResult Active(string id, string active)
        {
            if (!CheckAdmin())
                return RedirectToAction("Index", "Home");

            DataRepository dr = new DataRepository();
            dr.UserProvider.Active(int.Parse(id), active);

            return Content("");
        }

        [Authorize]
        [HttpGet]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(FormCollection collection)
        {
            ViewData["Success"] = "";

            string passwordOld = collection["passwordOld"];
            string passwordNew = collection["passwordNew"];
            string rePasswordNew = collection["rePasswordNew"];

            DataRepository dr = new DataRepository();
            USER user = dr.UserProvider.GetUserByUsername(User.Identity.Name);
            if (user != null)
            {
                string passwordDecrypt = MD5.Encrypt(passwordOld, User.Identity.Name + "key", true);
                if (user.Password.CompareTo(passwordDecrypt) != 0)
                {
                    ModelState.AddModelError("passwordOld", "Mật khẩu cũ không trùng khớp");
                }
                else
                {
                    if (passwordNew.Length < 6 || passwordNew.Length > 20)
                    {
                        ModelState.AddModelError("passwordNew", "Mật khẩu mới ít nhất 6 ký tự và nhỏ hơn 20 ký tự");
                    }
                    else
                    {
                        if (passwordNew.CompareTo(rePasswordNew) != 0)
                        {
                            ModelState.AddModelError("passwordNew", "Mật khẩu mới và mật khẩu mới nhập lại không trùng khớp");
                        }
                        else
                        {
                            string newPasswordEncrypt = MD5.Encrypt(passwordNew, User.Identity.Name + "key", true);
                            if (dr.UserProvider.update(user.ID, newPasswordEncrypt))
                            {
                                ViewData["Success"] = "Thay đổi mật khẩu thành công!";
                            }
                            else
                            {
                                ViewData["Success"] = "Thay đổi mật khẩu không thành công!";
                            }
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("userlost", "Người dùng " + User.Identity.Name + " không tồn tại");
            }

            return View();
        }
    }
}
